<?php

require_once("../models/config.php");
require_once("../ui.php");
include_once("bar.graph.php");

if (!isUserViewAuthorized()) {
	echo "Unauthorized access";
	die();
}

global $loggedInUser;
global $db;

function createToolUsageSqlCommand($toolsCategory) {

	$sql = "SELECT `debugging_Tools`.`Name` AS ToolName, COUNT(*) AS Total FROM `debugging_Tool_Usages` JOIN `debugging_Tools` ON `Debugging_Tool` = `debugging_Tools`.`Id` JOIN `debugging_Reports` ON `Debugging_Report` = `debugging_Reports`.`Id` JOIN `userCake_Users` ON `debugging_Reports`.`User` = `userCake_Users`.`User_ID` JOIN `debugging_Tool_Categories` ON `debugging_Tools`.`CategoryId` = `debugging_Tool_Categories`.`Id`
	
	WHERE (`userCake_Users`.`Group_Id` = " . STANDART_USER_GROUP_ID . ") AND (`debugging_Tool_Categories`.`Id` = '$toolsCategory')
	GROUP BY `debugging_Tools`.`Id`
	ORDER BY Total DESC";
		
	return $sql;
}

$category = readGet('categoryId');
if (!is_numeric($category)) {
	echo "Category id " . htmlspecialchars($category) . " is not numeric";
	return;
}

$sql = "SELECT `Name` AS Name FROM `debugging_Tool_Categories` WHERE `Id` = $category";
$result = $db->sql_query($sql);
if (!$result) {
	$error = $db->sql_error();
	return;
}

$row = $db->sql_fetchrow();
$categoryName = $row['Name'];

$sql = createToolUsageSqlCommand($category);
$result = $db->sql_query($sql);
if (!$result) {
	$error = $db->sql_error();
	return;
}

$rows = $db->sql_fetchall();

$toolNames = array();
$uses = array(); 
foreach($rows as $i => $row) {
	$toolNames[] = $row['ToolName'];
	$uses[] = $row['Total'];
}

drawMyPlotGraph($uses, "Usages", $toolNames, "Tool subcategory", "Count of usages for tools in category '$categoryName'");

?>